//face point app.js

var areaWidth = 425;
var areaHeight = 600;
var _point = [];
var _canvasPoint = [];


var $ = function(id){return document.getElementById(id)};

var div = $('canvas-area');
div.style.width = areaWidth;
div.style.height = areaHeight;

var c = document.createElement('canvas');
c.id = 'c';
c.width = areaWidth;
c.height = areaHeight;
c.style.width = areaWidth;
c.style.height = areaHeight;
div.appendChild(c);

//var canvas = new fabric.CanvasEx('c');  // extend event
var canvas = new fabric.Canvas('c');  //normal event
this.__canvas = canvas;
var COLOR = '#FF0000';
var OPACITY = '1';

//upload file
var imageLoader = $('upload-button');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e){
    canvas.clear();

    var reader = new FileReader();
    reader.onload = function(event){
       
        fabric.Image.fromURL(event.target.result, function(oImg) {
            oImg.selectable = false;       
            oImg.scaleToWidth(areaWidth);            
            canvas.add(oImg);
            oImg.center();
        });
    }
    reader.readAsDataURL(e.target.files[0]);     
}
//init method
function init() { 
    fabric.Image.fromURL('./img/image.jpg', function(oImg) {
        oImg.selectable = false;       
        oImg.scaleToWidth(areaWidth);        
        canvas.add(oImg);
        oImg.center();
    });
}

canvas.on('mouse:down', function (options){
    var x = options.e.offsetX;
    var y = options.e.offsetY;
    insertPoint(x, y);
    console.log(x + ', ' + y);
});

var outputText = $('txt-out');
function insertPoint(x, y){
    if (_point.length < 14) {

        var point = new fabric.Circle({
          radius: 10, 
          fill: 'green', 
          left: x-10, 
          top: y-10,
          selectable: false
        });

        canvas.add(point);
        var location = {x: x, y: y};
        _point.push(location);

        _canvasPoint.push(point);
        outputText.innerHTML = JSON.stringify(_point).toString();
    }
}

document.onkeydown = onKeyDownHandler;
function onKeyDownHandler(e) {
   switch (e.keyCode) {
      case 46: // delete
         var activeObject = canvas.getActiveObject();
         if (activeObject !== null) {
            canvas.remove(activeObject);            
            canvas.renderAll();
            return;
        }
   }
};

var btnUndo = $('btn-undo');
btnUndo.onclick = function(){
    if (_point.length === 0) {
        _canvasPoint = [];
        return;
    }

    var index = _point.length - 1

    if (_canvasPoint[index].type === 'circle'){

        canvas.remove(_canvasPoint[index]);
        canvas.renderAll()
        _canvasPoint.splice(index, 1);
        _point.splice(index, 1);
    }
}

//init();